from rest_framework import serializers
from .models import Roles, Users, Menus, Categories, Rights


class RolesSerializer(serializers.ModelSerializer):
    class Meta:
        model = Roles
        fields = '__all__'


# 单字段验证 多字段验证 字段选项验证 字段类型验证
# 外部设置  验证字段类型
def valid_mobile(value):
    import re
    if re.match('1[356789]\d{9}$', value) is None:
        raise serializers.ValidationError('输入的手机号格式不合法')


class UserSerializer(serializers.ModelSerializer):
    role_name = serializers.StringRelatedField(read_only=True)

    class Meta:
        model = Users
        fields = '__all__'
        extra_kwargs = {
            'mg_state': {'default': False},
            'password': {'write_only': True},
            'mobile': {'validators': [valid_mobile]},
        }

    # 验证单一字段
    # def validate_mobile(self, value):
    #     import re
    #     if re.match('1[356789]\d{9}$', value) is None:
    #         raise serializers.ValidationError("手机号格式不合法")
    #     return value
    # 验证一条或多条字段
    # def validate(self, attrs):
    #     import re
    #     if re.match('1[356789]\d{9}$', attrs['mobile']) is None:
    #         raise serializers.ValidationError('手机号格式不合法')
    #     return attrs


class UpdateUserSerializer(serializers.ModelSerializer):
    role_name = serializers.StringRelatedField(read_only=True)
    role_name_id = serializers.IntegerField(allow_null=True, required=False, write_only=True)

    class Meta:
        model = Users
        extra_kwargs = {
            'password': {'read_only': True},
            'username': {'read_only': True},
            'mobile': {'validators': [valid_mobile]},
        }
        exclude = ('password',)

    # 验证单一字段
    # def validate_mobile(self, value):
    #     import re
    #     if re.match('1[356789]\d{9}$', value) is None:
    #         raise serializers.ValidationError("手机号格式不合法")
    #     return value


# print(UserSerializer())
class MenuSerializer(serializers.ModelSerializer):
    class Meta:
        model = Menus
        fields = '__all__'

    def get_fields(self):
        fields = super(MenuSerializer, self).get_fields()
        fields['children'] = MenuSerializer(many=True)
        return fields


class RightSerializer(serializers.ModelSerializer):
    class Meta:
        model = Rights
        fields = '__all__'

    def get_fields(self):
        fields = super(RightSerializer, self).get_fields()
        fields['children'] = RightSerializer(many=True)
        return fields


class RightsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Rights
        fields = '__all__'


class CategoriesSerializer(serializers.ModelSerializer):
    class Meta:
        model = Categories
        fields = '__all__'
        extra_kwargs = {
        }

    def get_fields(self):
        fields = super(CategoriesSerializer, self).get_fields()
        fields['children'] = CategoriesSerializer(many=True, read_only=True)
        return fields


